﻿package com.tjsinfo.tjsoa.articles.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.tjsinfo.tjsoa.articles.bo.ITArticlesManage;
import com.tjsinfo.tjsoa.articles.bo.ManageSuperAction;
import com.tjsinfo.tjsoa.articles.bo.TArticlesRolesManage;
import com.tjsinfo.tjsoa.articles.vo.TIndexArticles;
import com.tjsinfo.tjsoa.common.SessionUser;
import com.tjsinfo.tjsoa.common.ToolKit;
import com.tjsinfo.tjsoa.system.bo.ITsystemRolesBo;
import com.tjsinfo.tjsoa.system.vo.User;

public class ArticlesListAction extends ManageSuperAction {
	
	private ITArticlesManage articlesManage;
	private TArticlesRolesManage articlesRolesManage;
	final static String ARTICLES_PAGE_SIZE = "20";
	final String ARTICLES_LIST_SIZE = "6";
	private String pageNo;
	private static HashMap<String, Integer[]> cidMap = new HashMap<String, Integer[]>();
	
	static{
		cidMap.put("jsgz", new Integer[]{919,920,921,922,923,924,925,926});
 		cidMap.put("gsdt", new Integer[]{928,929,930,931});
 		cidMap.put("gjjgl", new Integer[]{945,946,947,948,949,950});
 		cidMap.put("hyjy", new Integer[]{941,942,943,944});
	}
	public String getPageNo() {
		return pageNo;
	}

	public void setPageNo(String pageNo) {
		this.pageNo = pageNo;
	}

	public ITArticlesManage getArticlesManage() {
		return articlesManage;
	}

	public void setArticlesManage(ITArticlesManage articlesManage) {
		this.articlesManage = articlesManage;
	}
	
	public TArticlesRolesManage getArticlesRolesManage() {
		return articlesRolesManage;
	}

	public void setArticlesRolesManage(TArticlesRolesManage articlesRolesManage) {
		this.articlesRolesManage = articlesRolesManage;
	}
	//韩卓 
    public ITsystemRolesBo itrb;
	
	public ITsystemRolesBo getItrb() {
		return itrb;
	}

	public void setItrb(ITsystemRolesBo itrb) {
		this.itrb = itrb;
	}
	
	public void setTsystemRolesBo(ITsystemRolesBo itrb) {
		this.itrb = itrb;
	}
	
	public ITsystemRolesBo getTsystemRolesBo(ITsystemRolesBo itrb) {
		return itrb;
	}
////
/**
 * 前台根据cid获取栏目内文章列表
 * 实现分页功能
 */
	public ActionForward getList(ActionMapping mapping, ActionForm form,
		HttpServletRequest request, HttpServletResponse response)
		throws Exception {
		
		String loginname = "";
		Integer userid = 1;
		User user = SessionUser.getUser(request);
		if(null != user){
		userid = user.getUser_id();
		loginname = user.getUsername();
		}
		request.setAttribute("loginname", loginname);
		
		Integer cid = Integer.parseInt(request.getParameter("cid"));
		this.pageNo=request.getParameter("pageNo");
		Integer articlesTotalCount = articlesManage.findByCid(cid,"0","10").getTotalCount();
		Integer allPages = getAllPages(articlesTotalCount,Integer.parseInt(ARTICLES_PAGE_SIZE)); //
		String startNum = countStartNum(this.pageNo,allPages);		

		String cname =  articlesRolesManage.findById(cid).getName();
		List<TIndexArticles> articlesList=articlesManage.findByCid(cid,startNum,ARTICLES_PAGE_SIZE).getItems();
		request.setAttribute("cname",cname);
		request.setAttribute("cid", request.getParameter("cid"));
		request.setAttribute("articlesTotalCount", String.valueOf(articlesTotalCount));
		request.setAttribute("pageNo", pageNo);
		request.setAttribute("allPages", String.valueOf(allPages));
		request.setAttribute("articlesList", articlesList);
		
		//导航
		try {
			String menu=itrb.getMenuList(request,ToolKit.getSessionUser(request).getPermission());
			request.setAttribute("menu", menu);
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("Exception", e);
		}
		
		putRightArticlesList(request);
		return mapping.findForward(OPENLIST);
	}

/**
 * 计算总页数
 * @param a 总条目数
 * @param b 每页包含条目数
 * @return 总页数
 */
	public   int   getAllPages(int   a,int   b)   { 
		return(((double)a/(double)b)> (a/b)?a/b+1:a/b); 
		} 
			
/**
 * 前台根据uuid获取文章显示信息
 */
	   public ActionForward viewArticle(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response){
			try {

				String loginname = "";
				Integer userid = 1;
				User user = SessionUser.getUser(request);
				if(null != user){
				userid = user.getUser_id();
				loginname = user.getUsername();
				}
				request.setAttribute("loginname", loginname);
				
				String articles_uuid=request.getParameter("uuid");
			    TIndexArticles articles = articlesManage.findByID(articles_uuid);
			    Integer cid = articles.getCid();    //获取cid
			    String strUrl=articles.getUrl();
			    String strUploadFile = articles.getUploadFile();
		        String strFileUrl = "";
		        String FileUrl[] = {};
			    String serverName = "RQOAserver";
			    String conpathString = "";
			    String stopname = articlesRolesManage.findById(cid).getDescription();
			    
			  //导航
				try {
					String menu=itrb.getMenuList(request,ToolKit.getSessionUser(request).getPermission());
					request.setAttribute("menu", menu);
				} catch (Exception e) {
					e.printStackTrace();
					request.setAttribute("Exception", e);
				}
			    
		    	if(stopname!=null){
				    	if(stopname.indexOf("server")>0){     //如果栏目的description字段里包含server这个字符串，则表明是分公司的新闻栏目，则页面抬头需要显示subtop.jsp
				    		serverName = stopname.trim();
				    		conpathString = "/"+ serverName.substring(0, 5);
				    	} 
				    }
		    	request.setAttribute("imageServer", getImgServer(request,serverName));
			    if (strUrl!=null & !"".equals(strUrl)){  
			    	//如果链接字段不为空，则直接在新窗口中打开链接
			    	if (strUrl.indexOf("http:")<0){
			    		strUrl=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/"+strUrl;
			    	}
			    	request.setAttribute("linkUrl", strUrl);
			    	return mapping.findForward(LINK);
			    }
			    else if ((!"".equals(articles.getIsFile()))& strUploadFile.length()>0){ 
			    	//有附件，并且isfile字段值为‘1’时，直接打开附件
			    	request.setAttribute("articles", articles);
			    	request.setAttribute("content", downloadHtmlFile(articles_uuid,request)); //从html文件中读取正文，并将正文传递给页面		
			    	String cname =  articlesRolesManage.findById(articles.getCid()).getName();
			    	request.setAttribute("cname", cname);	
			    	putRightArticlesList(request);

			    	Document doc = Jsoup.parse(strUploadFile);
			    	Elements links = doc.select("a[href]");
			    	for(Element link : links){
			    		String linkHref = link.attr("href"); 
			    		try{
							strFileUrl = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+linkHref;
						} catch (Exception e) {
							strFileUrl = "";
						}
						FileUrl = insert(FileUrl, strFileUrl);
			    	}
//			    		String fileName = strFileUrl.substring(strFileUrl.lastIndexOf("/")+1);
						request.setAttribute("linkUrl", FileUrl);
			    	
//					Element url = doc.select("a[href]").first();
					
			    	return mapping.findForward(LINK);
			    }
			    else if ("4".equals(articles.getIsFile())& strUploadFile.length()>0){ 
			    	//有附件，并且isfile字段值为‘4’时，用soa插件打开附件

			    	Document doc = Jsoup.parse(strUploadFile);
					Element url = doc.select("a[href]").first();
					try{
						strFileUrl = request.getScheme()+"://"+ getImgServer(request,serverName) + "/articles/docview.jsp?docUrl=" + conpathString + url.attr("href");
					} catch (Exception e) {
						strFileUrl = "";
					}
					request.setAttribute("linkUrl", strFileUrl);
			    	return mapping.findForward(LINK);
//					try{
//						strFileUrl = url.attr("href");
//					} catch (Exception e) {
//						strFileUrl = "";
//					}
//					request.setAttribute("docUrl", strFileUrl);
//			    	return mapping.findForward("docview");
			    }else{ 
			    	//将文章对象传递给页面
			    	request.setAttribute("articles", articles);
			    	//通过cid获取栏目名称并转换为拼音，存入session
			    	request.setAttribute("content", downloadHtmlFile(articles_uuid,request)); //从html文件中读取正文，并将正文传递给页面		
			    	String cname =  articlesRolesManage.findById(articles.getCid()).getName();
			    	request.setAttribute("cname", cname);	
			    	putRightArticlesList(request);
					request.setAttribute("imageServer", getImgServer(request,serverName));
					if ("2".equals(articles.getIsFile())||"3".equals(articles.getIsFile()) ) //宽表格显示
					{
						return mapping.findForward(OPENBIGVIEW);
					}else{
						return mapping.findForward(OPENVIEW);
					}
			    }
			} catch (Exception e) {
				return mapping.findForward(FAILED);
			}
		}
	   public static String[] insert(String[] arr, String str)
	   {
	   int size = arr.length;
	   
	   String[] tmp = new String[size + 1];
	   
	   System.arraycopy(arr, 0, tmp, 0, size);
	   
	   tmp[size] = str;
	   
	   return tmp;
	   }

/**
 * 显示检索结果列表
 * 
 */
	public ActionForward searchArticles(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
				
			String strSearch = request.getParameter("_search");
			Integer cid= Integer.valueOf(request.getParameter("_cid"));
			this.pageNo= request.getParameter("pageNo");
			Integer articlesTotalCount = articlesManage.findByCidSearch(cid,strSearch,"0","1").getTotalCount();
			Integer allPages = getAllPages(articlesTotalCount,Integer.parseInt(ARTICLES_PAGE_SIZE));
			String startNum = countStartNum(pageNo,allPages);
			String cname = articlesRolesManage.findById(cid).getName();
			List<TIndexArticles> articlesList=articlesManage.findByCidSearch(cid,strSearch,startNum,ARTICLES_PAGE_SIZE).getItems();
			request.setAttribute("cname",cname);
			request.setAttribute("cid", request.getParameter("_cid"));
			request.setAttribute("pageNo", pageNo);
			request.setAttribute("allPages", String.valueOf(allPages));
			request.setAttribute("articlesList", articlesList);
			putRightArticlesList(request);
			return mapping.findForward(OPENLIST);
		} 

	
/**
 * 计算起始记录数
 * @param pageNo 当前页码
 * @param allPages 总页码
 * @return
 */
		private String countStartNum(String pageNo, Integer allPages) {
			// TODO Auto-generated method stub
			String startNum = ""; 
			if (pageNo==null || "0".equals(pageNo)){
				this.pageNo="1";
				startNum= "0";
			}else{
				Integer ipageNo=Integer.parseInt(pageNo);
				if (ipageNo>allPages)
				{
					ipageNo=allPages;
				}
				startNum = String.valueOf((ipageNo-1)*Integer.parseInt(ARTICLES_PAGE_SIZE));
			}
			return startNum;
		}

/**
 * 文章列表页及文章显示页面右侧新闻及通知栏目内容查询
 * @param request
 */
	private void putRightArticlesList(HttpServletRequest request){
			request.setAttribute("newsarticlesList", articlesManage.findByCid(901,"0","8").getItems());
			request.setAttribute("noticearticlesList", articlesManage.findByCid(902,"0","8").getItems());		 
	 }
	
	 /**
	  * 以json格式返回新闻或通知栏目链接内容
	  * @param mapping
	  * @param form
	  * @param request
	  * @param response
	  * @return
	  * @throws Exception
	  */	 
	 	 public ActionForward jsonMenuList(ActionMapping mapping, ActionForm form,
	 				HttpServletRequest request, HttpServletResponse response)
	 				throws Exception {
	 					
	 				Integer cid = Integer.parseInt(request.getParameter("cid")); //cid 栏目ID
	 				String stritems = request.getParameter("items");  //items 标识返回记录条数
	 				Integer size = Integer.parseInt(request.getParameter("size")); //size 标识标题字段保留的字符长度
	 				String sdate = request.getParameter("sdate"); //如果date不为空，则增加对有效日期的检索
	 				List<TIndexArticles> menuList = new ArrayList<TIndexArticles>();
	 				if (sdate==null || "".equals(sdate)){
	 					menuList=articlesManage.findByCid(cid,"0",stritems).getItems();
	 				}else{
	 					Date date = new Date();
	 					menuList=articlesManage.findByCid(cid,"0",stritems,date).getItems();
	 				}
	 				try {
	 					JSONArray menuArray = new JSONArray();
		 				for (TIndexArticles articlesL : menuList) {
		 					JSONObject object = new JSONObject();
		 					object.put("uuid", articlesL.getUuid());
		 					String strTitle = articlesL.getTitle();
		 					if(strTitle.length()>size){
		 						strTitle = strTitle.substring(0, size-1)+"...";
		 					}
		 					object.put("title", strTitle);
		 					menuArray.put(object);
		 				}
		 				response.getWriter().print(menuArray);
	 				} catch (IOException e) {
	 					// TODO Auto-generated catch block
	 					e.printStackTrace();
	 				} 
	 				return null;
	 			} 	 
/**
 * 显示子栏目列表
 */
	 public ActionForward newSubSectionList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	 		throws Exception {
		 
		 	String itemString="6"; //每栏目显示标题的条数
		 	Integer size = 33;  //标题显示长度
		   	String cidtype = request.getParameter("type");
		   	Integer [] cidarray = cidMap.get(cidtype);
		   	try {
					JSONArray roleArray = new JSONArray();
					List<TIndexArticles> menuList = new ArrayList<TIndexArticles>();	
					for(int i = 0;i < cidarray.length;i++){
						JSONObject roleObject = new JSONObject();
						JSONArray menuArray = new JSONArray();
						roleObject.put("cname",articlesRolesManage.findById(cidarray[i]).getName());
						roleObject.put("cid", cidarray[i]);
						menuList= articlesManage.findByCid(cidarray[i],"0",itemString).getItems();
		 				for (TIndexArticles articlesL : menuList) {
		 					JSONObject object = new JSONObject();
		 					object.put("uuid", articlesL.getUuid());
		 					String strTitle = articlesL.getTitle();
		 					if(strTitle.length()>size){
		 						strTitle = strTitle.substring(0, size-1)+"...";
		 					}
		 					object.put("title", strTitle);
		 					menuArray.put(object);
		 				}
		 				roleObject.put("artilesList", menuArray);
		 				roleArray.put(roleObject);
					}
					
 				response.getWriter().print(roleArray);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
		   	
	 		
	 					   
	 		return null;
	}  		 
	
	 /**
	  * 显示通讯录
	  */
	 	 public ActionForward addressView(ActionMapping mapping, ActionForm form,
	 			HttpServletRequest request, HttpServletResponse response)
	 	 		throws Exception {
	 		try {
				String articles_uuid1="b4f81059f7f24b3ea2814b874cad5c95";
				String articles_uuid2="d49fb94cab554e91be69f8046a3604be";
			    	request.setAttribute("content1", downloadHtmlFile(articles_uuid1,request)); //从html文件中读取正文，并将正文传递给页面		
			    	request.setAttribute("content2", downloadHtmlFile(articles_uuid2,request)); //从html文件中读取正文，并将正文传递给页面		
 					return mapping.findForward("addressview");
			    			    
			} catch (Exception e) {
				return mapping.findForward(FAILED);
			}
		} 
}
